//
//  HistoryList.swift
//  test1
//
//  Created by Apple on 2021/6/8.
//

/*
 参数：
 callBack(可选):使用的回调函数
 */

import SwiftUI
extension String {
//    func contains(find: String) -> Bool{
//        return self.range(of: find) != nil
//    }
    func containsIgnoringCase(find: String) -> Bool{
        return self.range(of: find, options: .caseInsensitive) != nil
    }
}
extension Array where Element == History {
    func lastThreeElement() -> [History] {
        var res = [History]()
        for index in 0..<count where index >= count - 3 {
            res.append(self[index])
        }
        return res
    }
}

struct HistoryList: View {

    @EnvironmentObject var modelData: HistoryListModelData
    // 获取历史列表的最后三个元素
    var list : [History] {
        //modelData.HistoryList.lastThreeElement()
        HistoryManager.getRecentHistoryList(limit: 3)
    }
    var matchList : [History] {
        HistoryManager.getCachedHistoryList().filter{ (item) ->
            Bool in
            return item.url.containsIgnoringCase(find: modelData.Searchtext) ||
                item.title.containsIgnoringCase(find: modelData.Searchtext)
        }
    }
    
    let data: Data = (UIImage(systemName: "clock")?.pngData())!
    
    var callBack : ViewCallBack?
    var body: some View {
        ScrollView {
            VStack{
                if modelData.Searchtext == ""{
                    ForEach(list, id:\.id) { item in
                        HistoryListItem(image: Image(uiImage: UIImage(data: item.faviconData ?? data)!), title: item.title, url: item.url, callBack: self.callBack)
                            .transition(.opacity)
                            .animation(.linear)
                    }
                } else {
                    ForEach(matchList, id:\.id) { item in
                        HistoryListItem(image: Image(uiImage: UIImage(data: item.faviconData ?? data)!), title: item.title, url: item.url, callBack: self.callBack)
                            .transition(.opacity)
                            .animation(.linear)
                    }
                }
            }
        }
    }
}

struct HistoryList_Previews: PreviewProvider {
    static var previews: some View {
        HistoryList()
            .environmentObject(HistoryListModelData())
    }
}
